<!-- 治疗任务-划扣 -->
<template>
  <div>
    <Dialog :title="title" :visible="visible" :button-text="textBtn" :reveal="true" :loading="loading" class="dialogStyle two-columns" @confirm="submitForm" @close="handleClose">
      <!-- <p class="ps pTwo"><span><strong>顾客</strong></span></p> -->
      <UserInfo :info-id="userInfo.customerId" />
      <p class="ps pTwo"><span><strong>项目划扣</strong></span></p>
      <el-table ref="projectTable" :data="cureTableData" border :row-class-name="tableColor" @select="onTableSelect" @selection-change="handleSelectionChange">
        <el-table-column label="选择" type="selection" width="55" />
        <el-table-column label="项目名称" prop="projectName" align="center" />
        <!-- <el-table-column label="项目属性" prop="projectType" align="center" /> -->
        <el-table-column label="剩余次数" prop="residueDegree" align="center" />
        <el-table-column label="执行数量" prop="executionQuantity" align="center">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.executionQuantity" controls-position="right" :min="1" :max="scope.row.usageCount-0" :disabled="scope.row.selected" />
          </template>
        </el-table-column>
      </el-table>
      <p v-if="formInline.selectProjects" class="ps pTwo"><span><strong>主理登记</strong></span></p>
      <el-form ref="formInlineRef" :inline="true" :model="formInline" :rules="formInlineRules" label-width="100px" label-position="right">
        <div v-for="p in formInline.selectProjects" :key="p.id">
          <el-row class="rows">
            <el-col :span="24">
              {{ p.productAttributes }}--{{ p.projectName }}
            </el-col>
          </el-row>
          <div v-if="p.productAttributes==='手术项目'">
            <el-row>
              <el-col :span="12">
                <el-form-item label="主诊医生：" verify prop="attendingDoctorName" empty-message="请选择主诊医生">
                  <el-select v-model="p.attendingDoctorName" class="el-select-y" value-key="id" placeholder="请选择主诊医生" style="width: 237.5px;" @change="(val)=>{changeAtteDoc(val, p)}">
                    <el-option v-for="item in allDoctorOptions" :key="item.id" :label="item.usrName" :value="item" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="治疗师：" prop="therapeutistName">
                  <el-select v-model="p.therapeutistName" class="el-select-y" placeholder="请选择治疗师">
                    <el-option v-for="item in allDoctorOptions" :key="item.id" :label="item.usrName" :value="item.usrName" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="美疗师：" prop="beautyTherapistName">
                  <el-select v-model="p.beautyTherapistName" class="el-select-y" placeholder="请选择美疗师">
                    <el-option v-for="item in allNurseOptions" :key="item.id" :label="item.name" :value="item.name" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="护士：" prop="nurseName">
                  <el-select v-model="p.nurseName" class="el-select-y" placeholder="请选择护士">
                    <el-option v-for="item in allNurseOptions" :key="item.id" :label="item.name" :value="item.name" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="备注：" prop="remarks" class="remarkCss">
                  <el-input v-model="p.remarks" class="box-yy" placeholder="请输入备注" type="textarea" />
                </el-form-item>
              </el-col>
            </el-row>
          </div>
          <div v-else-if="p.productAttributes==='美容项目'">
            <el-row>
              <el-col :span="12">
                <el-form-item label="主治医生：" prop="chiefSurgeonName">
                  <el-select v-model="p.chiefSurgeonName" class="el-select-y" placeholder="请选择主治医生">
                    <el-option v-for="item in allDoctorOptions" :key="item.id" :label="item.usrName" :value="item.usrName" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="麻醉医生：" prop="anesthesiologistName">
                  <el-select v-model="p.anesthesiologistName" class="el-select-y" placeholder="请选择麻醉医生">
                    <el-option v-for="item in allDoctorOptions" :key="item.id" :label="item.usrName" :value="item.usrName" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="助理医生：" prop="assistantDoctorName">
                  <el-select v-model="p.assistantDoctorName" class="el-select-y" placeholder="请选择助理医生">
                    <el-option v-for="item in allDoctorOptions" :key="item.id" :label="item.usrName" :value="item.usrName" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="把关医生：" prop="checkDoctorName">
                  <el-select v-model="p.checkDoctorName" class="el-select-y" placeholder="请选择把关医生">
                    <el-option v-for="item in allDoctorOptions" :key="item.id" :label="item.usrName" :value="item.usrName" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="巡回护士：" prop="circulatingNurseName">
                  <el-select v-model="p.circulatingNurseName" class="el-select-y" placeholder="请选择巡回护士">
                    <el-option v-for="item in allNurseOptions" :key="item.id" :label="item.name" :value="item.name" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="器械护士：" prop="instrumentNurseName">
                  <el-select v-model="p.instrumentNurseName" class="el-select-y" placeholder="请选择器械护士">
                    <el-option v-for="item in allNurseOptions" :key="item.id" :label="item.name" :value="item.name" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="备注：" prop="remarks" class="remarkCss">
                  <el-input v-model="p.remarks" class="box-yy" placeholder="请输入备注" type="textarea" style="width: 578px;" />
                </el-form-item>
              </el-col>
            </el-row>
          </div>
          <div v-else>
            <el-row>
              <el-col :span="12">
                <el-form-item label="主理医生：" prop="chiefPhysicianName">
                  <el-select v-model="p.chiefPhysicianName" class="el-select-y" placeholder="请选择主理医生">
                    <el-option v-for="item in allDoctorOptions" :key="item.id" :label="item.usrName" :value="item.usrName" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="护士：" prop="nurseName">
                  <el-select v-model="p.nurseName" class="el-select-y" placeholder="请选择护士">
                    <el-option v-for="item in allDoctorOptions" :key="item.id" :label="item.usrName" :value="item.usrName" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="备注：" prop="remarks" class="remarkCss">
                  <el-input v-model="p.remarks" class="box-yy" placeholder="请输入备注" type="textarea" />
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </div>

        <p class="ps pTwo"><span><strong>耗材登记</strong></span></p>
        <el-table :data="suppliesTableData" border :row-class-name="tableColor" @select="onTableSelect" @selection-change="handleSelectionSupplies">
          <el-table-column label="选择" type="selection" width="55" />
          <el-table-column label="项目名称" prop="projectName" align="center" />
          <el-table-column label="耗材" prop="materialMedicineName" align="center" />
          <el-table-column label="消耗数量" align="center">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.consumptionQuantity" controls-position="right" :min="1" :max="scope.row.usageCount-0" :disabled="scope.row.selected" />
            </template>
          </el-table-column>
          <el-table-column label="特殊备注" align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.specialRemarks" type="textarea" :rows="1" placeholder="请输入备注" />
            </template>
          </el-table-column>
        </el-table>
        <p class="ps pTwo"><span><strong>回访计划</strong></span></p>
        <!-- <el-form ref="visitFormRef" :model="visitForm" label-width="100px" label-position="right"> -->
        <!-- <el-form-item label="设定回访："> -->
        <el-form-item>
          <el-row v-for="(item,i) in ReturnVisitRules" :key="i" style="margin-top: 10px">
            <el-col>
              默认计划{{ i+1 }}：第{{ item.returnDay }}天
            </el-col>
            <el-col>
              回访时间：{{ item.returnTime }} 回访人：{{ item.revisiterName }}
            </el-col>
          </el-row>
          <ul>
            <li v-for="(items,i) in plainData" :key="i">
              <span>
                计划{{ i+1+ReturnVisitRules.length }}
              </span>
              <el-row type="flex">
                <el-col :span="11">
                  <el-form-item label="回访日期：" prop="plannedReturnVisitDate">
                    <el-date-picker v-model="items.plannedReturnVisitDate" type="date" placeholder="选择日期" value-format="yyyy-MM-dd" />
                  </el-form-item>
                </el-col>
                <el-col :span="11">
                  <el-form-item label="回访人：" prop="revisiterName">
                    <el-select v-model="items.revisiterName" class="el-select-y" placeholder="选择回访人" value-key="id">
                      <el-option v-for="item of attributionConsultants" :key="item.id" :label="item.usrName" :value="item" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="2">
                  <el-button type="text" @click="deletePlain(i)">删除</el-button>
                </el-col>
              </el-row>
            </li>
            <span class="spn buttons"><el-button @click="addPlain">+ 增加计划</el-button></span>
          </ul>
        </el-form-item>
      </el-form>
      <!-- <el-row type="flex" justify="center">
        <el-col :span="3">
          <el-button type="primary" :loading="loading" @click="submitForm">提交</el-button>
        </el-col>
        <el-col :span="3">
          <el-button @click="handleClose">取消</el-button>
        </el-col>
      </el-row> -->
    </Dialog>
  </div>
</template>
<script>
import Dialog from "@/components/Dialog/index";
import UserInfo from "@/components/UserInformation";
import { lookup, tableColor } from "@/utils/common.js";
export default {
  components: {
    Dialog,
    UserInfo,
  },
  props: {
    textBtn: {
      type: String,
      default: '',
    },
    selectedRow: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      cureTableData: [],
      tableColor,
      suppliesTableData: [],
      treatmentTaskId: '',
      formInline: {},
      // visitForm: {
      //   delivery: false,
      // },
      plainData: [{
        plannedReturnVisitDate: '',
        revisiterName: '',
      }],
      ReturnVisitRules: [],
      allDoctorOptions: [],
      allNurseOptions: [],
      attributionConsultants: [],
      projectIds: [],
      userInfo: {},
      // selected: true,
      selectProjects: [],
      selectConsumables: [],
      title: '划扣',
      visible: false,
      loading: false,
      formInlineRules: {
        attendingDoctorName: [
          { required: true, message: '请选择主治医生', trigger: 'change' },
        ],
      },
    };
  },
  mounted() {
    this.$emit('childMounted');
  },
  methods: {
    openDialog(row) {
      // this.visible = true;
      // this.userInfo = row;
      // this.loadCustomerOrderList();
      // this.getDoctorList();
      // this.getReturnVisitList();
      this.drawBtn(row);
    },
    loadCustomerOrderList() {
      this.$api['reception/subscribe/customerIdAllByOrderListId']({ customerId: this.selectedRow.customerId }).then(resData => {
        if (resData.data) {
          resData.data.map(item => {
            this.$set(item, 'residueDegree', item.usageCount);
            this.$set(item, 'projectType', item.productAttributes);
            if (item.status === "未结束") {
              item.executionQuantity = 1;
              this.cureTableData.push(item);
              if (item.id === this.selectedRow.id) {
                this.toggleProjectSelection([item]);
              }
            }
          });
          this.$set(this.formInline, "selectProjects", this.selectProjects);
        }
      })
        .catch(err => {
          console.error(err);
        });
      this.attributionConsultant();
    },
    toggleProjectSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.projectTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.projectTable.clearSelection();
      }
    },
    onTableSelect(rows, row) {
      let selected = rows.length && rows.indexOf(row) !== -1;
      // console.log(selected, 'selected'); // true就是选中，0或者false是取消选中
      if (selected === 0 || selected === false) {
        selected = false;
      }
      return (row.selected = !selected);
    },
    async handleSelectionChange(val) {
      val.map(item => {
        this.$set(item, 'projectNo', item.productNo);
      });
      this.selectProjects = val;
      this.$set(this.formInline, "selectProjects", this.selectProjects);
      this.projectIds = [];
      this.suppliesTableData = [];
      val.map(item => {
        this.projectIds.push(item.projectId);
      });
      if (this.projectIds.length > 0) {
        const res = await this.$api['department/drawrecord/findbyLists']({ projectIds: this.projectIds });
        if (res.code !== 200) return this.$message.error(res.msg);
        res.data.map(item => {
          this.$set(item, 'materialMedicineName', item.name);
          this.$set(item, 'selected', true);
        });
        this.suppliesTableData = res.data;
      }
    },
    // 耗材选择
    handleSelectionSupplies(val) {
      val.map(item => {
        this.$set(item, 'materialMedicineId', item.id);
        this.$set(item, 'materialMedicineName', item.name);
      });
      this.selectConsumables = val;
    },
    changeAtteDoc(val, p) {
      p.attendingDoctorName = val.usrName;
      this.$set(this.formInline, "attendingDoctorName", val.usrName);
    },
    drawBtn(row) {
      this.userInfo = row;
      this.visible = true;
      this.treatmentTaskId = row.id;
      this.getCustomerIdAllByOrder(row);
      this.getReturnVisitList();
      this.getDoctorList();
      this.attributionConsultant();
    },
    async getCustomerIdAllByOrder(row) {
      const res = await this.$api['department/drawrecord/customerIdAllByOrderListId']({ customerId: row.customerId });
      if (res.code !== 200) return this.$message.error(res.msg);
      this.cureTableData = res.data;
      this.cureTableData.map(item => {
        this.$set(item, 'projectType', item.productAttributes);
        this.$set(item, 'residueDegree', item.usageCount);
        this.$set(item, 'executionQuantity', 1);
        this.$set(item, 'selected', true);
      });
    },
    async getReturnVisitList() {
      const res = await this.$api['department/drawrecord/returnVisitList']({ query: { type: '治疗后回访' }});
      if (res.code !== 200) return this.$message.error(res.msg);
      this.ReturnVisitRules = res.data;
      this.ReturnVisitRules.forEach(item => {
        this.$nextTick(() => {
          this.$set(item, 'plannedReturnVisitDate', item.returnTime);
          this.$set(item, 'revisiterName', item.returnName);
          this.$set(item, 'revisiterId', item.id);
        });
        const dates = new Date(new Date(item.createdTime).valueOf() + 24 * 60 * 60 * 1000 * Number(item.returnDay));
        const year = dates.getFullYear();
        const month = dates.getMonth() + 1;
        const day = dates.getDate();
        const rebackTime = year + "-" + month + "-" + day;
        this.$set(item, 'rebackTime', rebackTime);
      });
    },
    submitForm() {
      this.$refs.formInlineRef.validate(async(valid) => {
        if (valid) {
          this.plainData.map(item => {
            if (item.revisiterName) {
              this.$set(item, 'revisiterId', item.revisiterName.id);
              this.$set(item, 'revisiterName', item.revisiterName.usrName);
            } else {
              this.$set(item, 'revisiterId', null);
              this.$set(item, 'revisiterName', null);
            }
            if (item.plannedReturnVisitDate === "") {
              this.$set(item, 'plannedReturnVisitDate', null);
            }
          });
          this.visitDtoList = [...this.ReturnVisitRules, ...this.plainData];
          if (this.formInline.selectProjects) {
            this.formInline.selectProjects.forEach((item) => {
              // Object.assign(item, this.userInfo);
              this.$set(item, 'scratchConsumablesDtoList', []);
              this.selectConsumables.forEach((element) => {
                if (item.projectId === element.projectId) {
                  item.scratchConsumablesDtoList.push(element);
                }
              });
            });
          }
          this.loading = true;
          const res = await this.$api['department/order/addRecord']({ ...this.userInfo, deductionRecordDtoList: this.formInline.selectProjects, visitDtoList: this.visitDtoList, treatmentTaskId: this.treatmentTaskId });
          this.loading = false;
          if (res.code !== 200) return this.$message.error('添加划扣失败!');
          this.$message.success('添加划扣成功！');
          this.visible = false;
          this.$emit('success');
        }
      });
    },
    handleClose() {
      this.cureTableData = [];
      this.plainData = [{
        plannedReturnVisitDate: '',
        revisiterName: '',
      }];
      this.$emit('componentResult', "close");
      this.loading = false;
      this.visible = false;
    },
    // 增加计划
    addPlain() {
      this.plainData.push({
        plannedReturnVisitDate: '',
        revisiterName: '',
      },);
    },
    // 删除计划
    deletePlain(index) {
      this.plainData.splice(index, 1);
    },
    async getDoctorList() {
      this.allDoctorOptions = lookup('主治医生');
    },
    async attributionConsultant() {
      this.attributionConsultants = lookup('咨询师');
    },
  },
};
</script>
<style lang="scss" scoped>
.formInlineCss {
  margin-top: 20px;
}
.rows{
  font-size: 15px;
  font-weight: 700;
  margin-bottom: 12px;
  text-align: center;
}
.box-yy /deep/.el-textarea__inner{
  border: 1px solid #9baed3;
  }
  .dialogStyle{
    /deep/.el-form-item{
      display: flex;
    }
/deep/.el-form-item__content{
    flex: 1;
  }
  }
</style>
